/*		Filename: 	database_manager.h
 *		Author:		彭望
 *		Date:		2012-01-10
 *		Use:		定义卡管理系统的结构
 */
#ifndef DATABASE_MANAGER_H
#define DATABASE_MANAGER_H
#include "public.h"
#include "card_info.h"
#include "accounting_info.h"
#include "logger.h"

#include <map>
#include <libconfig.h++>
#include <sqlite3.h>



class CDatabaseManager
{
	public:
			enum DBType{
					DB_CARD			=		1000,
					DB_STANDARD 	=		1001,
					DB_FEE			=		1002,
					DB_FEE_RECORD	=		1003	
			};

			enum OPType{
					OP_CREATE_TABLE =		1000,
					OP_ADD			=		2000,
					OP_DELETE		=		2001,
					OP_UPDATE		=		2002,
					OP_QUERY		=		2003,
			};
	public:
			CDatabaseManager(const string& strConfigName);

			//提供卡管理
			RetCode_t add_card(const CCardInfo& info);
			RetCode_t delete_card(const CCardInfo& info);
			RetCode_t search_card(CCardInfo& info);
			RetCode_t update_card(const CCardInfo& info);

			//提供费用管理
			RetCode_t add_balance(const CCardInfo& info, double delta);
			RetCode_t cut_balance(const CCardInfo& info, double delta);
			RetCode_t query_balance(CCardInfo& info);

			//提供计费标准管理
			RetCode_t add_rule(const CAccountingInfo&);
			RetCode_t modify_rule(const CAccountingInfo&);
			RetCode_t query_rule(CAccountingInfo& );

	private:
			//负责所有初始化的工作
			RetCode_t init();
			//读取配置文件
			RetCode_t load_config(const string& strConfigName);
			//打开数据库
			RetCode_t open_db(const string& strDBFileame, sqlite3** pDB);
			//执行数据库语句
			RetCode_t exec_sql(sqlite3* db, const string& sql, void* res);
			//数据库回调函数
			static int card_callback(void *res, int argc, char **argv, char **azColName);
			//转换ptime为string
			string ptime2string(const ptime& );
			//将操作转换为sql语句
			string trans2SQL(OPType t, const CCardInfo& info);
			//将数据库返回结果转换为info
			static RetCode_t fill_card_info(const char* key, const char* value, CCardInfo& info);
	private:
			sqlite3* m_database;
			string m_dbName;
			string m_cardTableName;
			log4cpp::Category& logger;

};

typedef boost::shared_ptr<CDatabaseManager> DBManagerPtr;
#endif
